package core;

import response.*;
import java.util.Vector;

/**
 * GamePacket sent by the server.
 * BigEndian conversion is done within GamePacketStream.
 *
 * Method names are mostly matched with PyDatagram
 *
 * Example:
 * 	GamePacket packet = new GamePacket(Constants.SMSG_DICE_RES);
 *      packet.addUint16((short)result);
 *      return packet.getBytes();
 *
 *      //This makes internally prepares the packet to send
 *
 *      byte[0] = Lo of Packet Length = 0x04
 *      byte[1] = Hi of Packet Length = 0x00
 *      byte[2] = Lo of Constants.SMSG_DICE_RES = 0x1f
 *      byte[3] = Hi of Constants.SMSG_DICE_RES = 0x00
 *      byte[4] = Lo of Result = ?
 *      byte[5] = Hi of Result = 0x00
 *
 * @author genki, Gary
 */
public class GamePacket {

    private GamePacketStream buf = null;

    public GamePacket(short message_id) {
        buf = new GamePacketStream(message_id);
    }

    public void addInt16(short short_val) {
        buf.add(short_val);
    }

    public void addInt32(int int_val) {
        buf.add(int_val);
    }

    public void addUint16(short short_val) {
        buf.add(short_val);
    }

    public void addUint32(int int_val) {
        buf.add(int_val);
    }

    public void addBool(boolean i) {
        byte[] bytes = new byte[1];
        bytes[0] = (byte) (i ? 1 : 0);
        addBytes(bytes);
    }

    public void addBytes(byte[] bytes) {
        buf.add(bytes);
    }

    public void addFloat(float float_val) {
        addUint32(Float.floatToIntBits(float_val));
    }

    /**
     * add_string
     * @param str	string to add
     *
     *  Add the length of string
     *  Then, add the string
     */
    public void addString(String str) {
        buf.add((short) str.length());
        buf.add(str.getBytes());
    }

    /**
     * add_vector
     * @param vecString	vector<String> to add
     *
     *  Add the size of vecString
     *  Then, add each string by calling add_string.
     */
    public void addVectorString(Vector<String> vecString) {
        for (String itemName : vecString) {
            addString(itemName);
        }
    }

    public void addVectorFloat(Vector<Float> vecFloat) {
        for (float f : vecFloat) {
            addUint32(Float.floatToIntBits(f));
        }
    }

    public int size() {
        return buf.size();
    }

    public byte[] getBytes() {
        return buf.toByteArray();
    }
}

